package com.huazai.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 线程间中通信
 * if 中放wait可以产生虚假唤醒 说以用while
 *
 * @author huazai
 * @date 2024/2/2
 */
public class ThreadDemo2 {
    public static void main(String[] args) {
        final Share2 share = new Share2();
        new Thread(() -> {
            try {
                for (int i = 0; i < 5; i++) {
                    share.incr();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "aa").start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 5; i++) {
                    share.des();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "bb").start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 5; i++) {
                    share.incr();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "cc").start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 5; i++) {
                    share.des();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "dd").start();
    }
}

class Share2 {
    private int number = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void incr() throws InterruptedException {
        lock.lock();
        try {
            while (number != 0) {
                condition.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName() + "  number = " + number);
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public void des() throws InterruptedException {
        lock.lock();
        try {

            while (number == 0) {
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName() + "  number = " + number);
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }
}
